import { randomUUID } from 'crypto'
import dayjs from 'dayjs'
import fs from 'fs'
import { NextResponse } from 'next/server'
import path from 'path'

const saveFile = async (file: File) => {
  // 获取文件的 ArrayBuffer
  const bytes = await file.arrayBuffer()
  const buffer = Buffer.from(bytes)

  // 创建上传目录
  const dirName = '/uploads/' + dayjs().format('YYYY-MM-DD')
  const uploadDir = path.join(process.cwd(), 'public', dirName)
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true })
  }

  // 生成文件名：uuid + 原文件扩展名
  const fileName = randomUUID() + path.extname(file.name)
  const filePath = path.join(uploadDir, fileName)

  // 写入文件
  fs.writeFileSync(filePath, buffer)

  // 返回可访问的文件路径
  return `${dirName}/${fileName}`
}

export const POST = async (req: Request) => {
  try {
    const formData = await req.formData()
    const file = formData.get('file') as File

    if (!file) {
      return NextResponse.json({
        success: false,
        message: '请选择文件'
      })
    }

    // 保存文件并获取路径
    const filePath = await saveFile(file)

    return NextResponse.json({
      success: true,
      message: '上传成功',
      data: filePath
    })
  } catch (error) {
    console.error('Upload failed:', error)
    return NextResponse.json({
      success: false,
      message: '上传失败'
    })
  }
}
